#include "DemoMouseJoint.h"
#include"LSYEasyBody.h"
#include"LSYEasyWorld.h"
#include"Tool.h"

USING_NS_CC;

bool DemoMouseJoint::init()
{
	if (!AbstractLayer::init(b2Vec2(0, -10)))
	{
		return false;
	}
	return true;
}

void DemoMouseJoint::box2DAppReady()
{
	createBodies();
	player = LSYEasyBody::createCircle(b2Vec2(20, 100), 20);
}

void DemoMouseJoint::createBodies()
{
	auto size = Director::getInstance()->getWinSize();
	LSYEasyBody::createRectangle(b2Vec2(0, 0), size.width, size.height);
	LSYEasyBody::createCircle(b2Vec2(400, 0), 150, b2BodyType::b2_staticBody);
	LSYEasyBody::createCircle(b2Vec2(150, 0), 50, b2BodyType::b2_staticBody);
	LSYEasyBody::createCircle(b2Vec2(550, 0), 50, b2BodyType::b2_staticBody);
}

void DemoMouseJoint::createMouseJoint(b2Vec2 anchorB)
{
	b2BodyDef*  bd = new b2BodyDef;
	embd = pWorld->CreateBody(bd);
	
	b2Body* bodyB = player;
	b2MouseJointDef* jointDef = new b2MouseJointDef;
	jointDef->bodyA = embd;
	jointDef->bodyB = bodyB;
	jointDef->target = anchorB;
	jointDef->frequencyHz = 1;
	jointDef->dampingRatio = 0;
	jointDef->maxForce = bodyB->GetMass() * 20;
	
	mouseJoint = (b2MouseJoint*)pWorld->CreateJoint(jointDef);
}

bool DemoMouseJoint::onTouchBegan(cocos2d::Touch * touch, cocos2d::Event * unused_event)
{
	mousePoint.x = touch->getLocation().x*PTM_RADIO;
	mousePoint.y = touch->getLocation().y*PTM_RADIO;

	b2Body* bodyAtMouse = LSYEasyWorld::getBodyAt(mousePoint);
	if (bodyAtMouse != nullptr&&bodyAtMouse != player)
	{
		createMouseJoint(player->GetPosition());
		mouseJoint->SetTarget(mousePoint);
	}
	return true;
}

void DemoMouseJoint::onTouchEnded(cocos2d::Touch * touch, cocos2d::Event * unused_event)
{
	if (mouseJoint != nullptr)
		pWorld->DestroyJoint(mouseJoint);
	if (embd != nullptr)
		pWorld->DestroyBody(embd);
	embd = nullptr;
	mouseJoint = nullptr;
}
